package com.github.freewu.commons.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.os.Build;
import android.view.View;
import android.widget.TextView;

import com.lqkj.commons.R;

/**
 * Created by 杨哲 on 2016/4/28 0028.
 */
public class DialogUtils {

    static Dialog dialog;

    public static void showDialog(final Activity activity, String messageText, View.OnClickListener okBtnClickListener){
        showDialog(activity,messageText,okBtnClickListener,DialogFeature.NOT_CANCELABLE,DialogFeature.NOT_FINISH_ACTIVITY);
    }

    public static void showDialog(final Activity activity, String messageText, View.OnClickListener okBtnClickListener, DialogFeature... features){
        boolean isCancelable=false;
        boolean isFinishActivity=false;

        for(DialogFeature feature:features){
            if (feature==DialogFeature.CAN_CANCELABLE){
                isCancelable=true;
            }
            if (feature==DialogFeature.NOT_CANCELABLE){
                isCancelable=false;
            }
            if (feature==DialogFeature.FINISH_ACTIVITY){
                isFinishActivity=true;
            }
            if (feature==DialogFeature.NOT_FINISH_ACTIVITY){
                isFinishActivity=false;
            }
        }

        dialog = new Dialog(activity, R.style.dialog);

        dialog.setCancelable(isCancelable);
        View mView=View.inflate(activity.getApplication(), R.layout.dialog_normal,null);

        TextView message=(TextView)mView.findViewById(R.id.dialog_message);
        TextView ok=(TextView)mView.findViewById(R.id.dialog_ok);
        TextView cancel=(TextView)mView.findViewById(R.id.dialog_cannel);

        message.setText(messageText);
        ok.setOnClickListener(okBtnClickListener);

        final boolean finalIsFinishActivity = isFinishActivity;
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();

                if (finalIsFinishActivity){
                    activity.finish();
                }
            }
        });

        dialog.setContentView(mView);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (!activity.isDestroyed()) {
                dialog.show();
            }
        }else{
            if (!activity.isFinishing()){
                dialog.show();
            }
        }
    }

    public static void dismissDialog(){
        if (dialog!=null){
            if (dialog.isShowing()) {
                dialog.dismiss();
                dialog=null;
            }
        }
    }
}